var Message = require("./../models/message");
var Q = require('q');
const fs = require('fs')
const multiparty = require('multiparty');


var dbMessage = {};

//历史消息
dbMessage.history = function(option){
	 var deferred = Q.defer();
	 var req = {
	 	code: 1,
		message: '获取成功',
		data:{
			total:0,
			pageNum:'',
			pageSize:'',
			current:'',
			list:[]
		}
	 }
	 option = option || {};
	
	req.data.pageSize =  option.pageSize =  Number(option.pageSize) || 10;
	req.data.pageNum =  option.pageNum = Number(option.pageNum) || 1;
	req.data.current =  option.current = option.current || '';
	option.type = parseInt(option.type);
	var vaildType = [1,3,5]; //1:对客服讲话,2:对人讲话,3:系统广播,4:大厅全局聊天,5：机器人聊天
	 if(!option.name || ( vaildType.indexOf(option.type) == -1 && !option.fellow)){
	 	process.nextTick(function(){
	 		req.code = -3;
	 		req.message = "参数错误";
	 		deferred.reject(req);
	 		global.logger.info("参数错误:",JSON.stringify(option));	
	 	});
	 	return deferred.promise;
	 }
	 
	 var search = null;
	 if(option.type == 1){
	 	//客服搜索
	 	search = {"$or":[{username:option.name,type:option.type},{receive:option.name,type:option.type}]};
		global.logger.info("客服搜索:",search);
	 }else if(option.type == 4){
	 	search = {type:option.type};
	 	global.logger.info("全局搜索:",search);
	 }else if(option.type == 5){
		 search = {"$or":[{username:option.name,receive:option.fellow,type:option.type},{username:option.fellow,receive:option.name,type:option.type}]};
		 global.logger.info("机器人聊天:",search);
	 }else{
	 	search = {"$or":[{username:option.name,receive:option.fellow},{username:option.fellow,receive:option.name}]};
	 	global.logger.info("对话搜索:",search);
	 }
	
	
	  const task1 = new Promise((resolve, reject) => {
      const skip = parseInt((option.pageNum - 1) * option.pageSize)
      Message.find(search).sort({"time": -1,"_incId":-1}).skip(skip).limit(option.pageSize).exec((err, data) => {
        if (err) {
		  global.logger.error("数据库操作错误1:",err);
		  reject();
        } else {
           resolve(data);
        }
      })
    })
    const task2 = new Promise((resolve, reject) => {
      Message.count(search).exec((err, data) => {
        if (err) {
		  global.logger.error("数据库操作错误2:",err);
		  reject();
        } else {
          resolve(data);
        }
      })
    });
    Promise.all([task1, task2]).then((data) => {
      	req.data.list = data[0];
      	req.data.total = data[1];     	
      	deferred.resolve(req);
    },(error)=>{
    	req.code = -2;
 		req.message = "数据库操作错误";
    	deferred.reject(req);
    });
	
	
	return deferred.promise;
}


//图片上传
dbMessage.fileUp = function(option){
	
	var deferred = Q.defer();
	 var res = {
	 	code: 1,
		message: '上传成功',
	 }
	option = option || {};
	if(!option.req){
		process.nextTick(function(){
	 		req.code = -3;
	 		req.message = "参数错误";
	 		deferred.reject(req);
	 		global.logger.error("参数错误:",JSON.stringify(option));	
	 	});
	 	return deferred.promise;
	}
	var time = Date.now();
	
	//生成multiparty对象，并配置上传目标路径
    const form = new multiparty.Form()
    // //设置编辑
    form.encoding = 'utf-8'
    // //设置文件存储路径
    form.uploadDir = "./public/static/files/"
    // //设置单文件大小限制
    form.maxFilesSize = 2 * 1024 * 1024
    // form.maxFields = 1000;  设置所以文件的大小总和
    // 上传完成后处理

    
    form.parse(option.req, (err, fields, files) => {
      if (err) {
        global.logger.error('文件格式化错误:' + err);
        res.code = -6;
        res.message = '文件格式化错误';
        deferred.reject(res);
      } else {
      	
        const inputFile = files.upload[0];
        
        const uploadedPath = inputFile.path
        const array = inputFile.originalFilename.split('.')
        const imgtype = array[array.length - 1]
    
        const time = new Date().getTime() + Math.floor(Math.random()*1000000);
        const inPath = `./public/static/files/${time}.${imgtype}`; //重命名的路径
        // 判断是否存在./dist/static/files文件
        fs.stat('./public/static/files', (err, stats) => {
          if (JSON.stringify(stats) === undefined) {
            fs.mkdirSync('./public/static', 0777)
            fs.mkdirSync('./public/static/files', 0777)
          }
          storeFiles(uploadedPath, fields, inPath)
        });
      }
    });
    
    function storeFiles(uploadedPath, fields, inPath) {
      //重命名为真实文件名
      fs.rename(uploadedPath, inPath,  (err) => {
        if (err) {
          res.code = -6;
          res.message = '文件重命名错误';
          deferred.reject(res);
          global.logger.error(`rename error:${err}`)
        } else {
    
          //保存聊天记录
    	 const mess = {
            username: fields.username&&fields.username[0],
        	receive:fields.receive&&fields.receive[0],
            src: inPath.substring(8),
            type: fields.type&&fields.type[0],
            msg:fields.msg&&fields.msg[0],
            time:time
          }
          const message = new Message(mess)
          message.save((err, mess) => {
            if (err) {
            	 global.logger.error("数据库操作错误2:",err);
              	res.code = -2;
		 		res.message = "数据库操作错误";
		    	deferred.reject(res);
            }
            global.logger.info(mess);
            deferred.resolve(res);
          })		
        }
      });
    }
    
    return deferred.promise;
}

module.exports = dbMessage;